import {
  takeVersion,
  takeSend,
  takeReceive,
  takeDataChainCode,
  takeRegion,
  takeCrossNumber,
  takeOperateType,
  takeObjectId,
  takeSerialNumber,
  takeObjectNumber,
  ObjectIdFlag
} from "./protocol.js"

class Encode {
  constructor(result) {
    this.result = result
    this.version = takeVersion(result)
    this.send = takeSend(result)
    this.receive = takeReceive(result)
    this.dataChainCode = takeDataChainCode(result)
    this.region = takeRegion(result)
    this.crossNumber = takeCrossNumber(result)
    this.operateType = takeOperateType(result)
    this.objectId = takeObjectId(result)
    this.serialNumber = takeSerialNumber(result)
    this.objectNumber = takeObjectNumber(result)
  }

  response() {
    let resopnse_operate_type
    switch (this.operateType) {
      case 0x81:
        resopnse_operate_type = 0x84
        break;
      case 0x80:
        resopnse_operate_type = 0x83
        break;
    }
    let response = [0xfa, 0xfb, 0xfc, 0xfd, this.version, this.receive, this.send, this.dataChainCode, this.region]
    response.push(this.result[9,13])       // 信号机编码
    response.push(resopnse_operate_type)   // 操作类型
    response.push(this.objectId)           // 对象标志
    response.push(0x00, 0x00, 0x00, 0x00)  // 流水号
    response.push(this.objectNumber)       // 对象元素编号
    response.push(0x00, 0x00)              // 保留字节

    if (this.objectId === ObjectIdFlag._heart) {
      for (let i = 0; i < 50; i++) {
        response.push(0x00)
      }
    }
    
    let temp = response.slice(4)
    let sum = temp.reduce((preVal, currentVal, index, origin) => {
      return preVal += currentVal
    }, 0)
    console.log('sum=',sum,temp);
    let a = sum & 0xff
    let b = (sum >> 8) & 0xff
    response.push(a,b)
    return response
  }
}

export default Encode